var ws = require("nodejs-websocket")
var port = 3000; 
var count = 0;
// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
	console.log("New connection")
	count++;
	conn.nickname = "user" + count;
	var mes = {};
	mes.type = "enter"
	mes.data = 	conn.nickname ;
	boradcast(JSON.stringify(mes))
	conn.on("text", function (str) {
		console.log("Received "+str)
		var mes = {};
		mes.type = "message"
		mes.data = 	conn.nickname + '说' + str;
		boradcast(JSON.stringify(mes))
	})
	conn.on("close", function (code, reason) {
		console.log("Connection closed")
		var mes = {};
		mes.type = "leave"
		mes.data = 	conn.nickname
		boradcast(JSON.stringify(mes))
    })
    conn.on("error", function (err) {
		console.log("handle err",err)
	})
}).listen(port)
function boradcast(str){
	server.connections.forEach(function(connections){
		console.log(connections)
		connections.sendText(str)

	})
}
console.log("端口"+port)